package com.wjk.kylin.modules.system.position.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.modules.system.position.entity.Position;
import com.wjk.kylin.modules.system.position.mapper.PositionMapper;
import com.wjk.kylin.modules.system.position.service.IPositionService;
import com.wjk.kylin.modules.system.user.service.IUserPositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;


/**
 * <p>
 * 岗位表 服务实现类
 * </p>
 *
 * @author wangjkui
 * @since 2020-06-01
 */
@Service
@Transactional(readOnly = true)
public class PositionServiceImpl extends ServiceImpl<PositionMapper, Position> implements IPositionService {
    @Autowired
    private IUserPositionService userPositionService;

    @Override
    @Transactional(readOnly = false)
    public boolean save(Position position) {
        //1.判断code是否已经存在
        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        wrapper.eq("code", position.getCode());
        int count = this.count(wrapper);
        if(count > 0){
            throw new BusinessException("岗位编码已存在，请重新添加");
        }
        position.preInsert();
        return super.save(position);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean update(Position position) {
        //1.判断code是否已经存在
        QueryWrapper<Position> wrapper = new QueryWrapper<>();
        wrapper.eq("code", position.getCode());
        wrapper.ne("id", position.getId());
        int count = this.count(wrapper);
        if(count > 0){
            throw new BusinessException("岗位编码已存在，请重新修改");
        }

        position.preUpdate();
        return super.updateById(position);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean deleteByIds(String[] positionIds) {
        List<String> list = Arrays.asList(positionIds);
        //1.删除用户岗位关联数据
        userPositionService.deleteByPositionIds(list);

        return super.removeByIds(list);
    }

    @Override
    public IPage<Position> findPage(Page<Position> page, Position position) {
        return baseMapper.findPage(page,position);
    }

    @Override
    public List<String> findPositionListByUserId(String userId) {
        return userPositionService.findPositionListByUserId(userId);
    }
}
